﻿using System.Collections.Generic;
using System.Linq;

namespace eAtlantida.Tools.Operations.GenerateOperations
{
    public class GenerateOperation : Operation
    {
        public const string Name = "generate";

        private void AttachEvents(Operation operation)
        {
            operation.SendMessage += WriteMessage;
        }

        private readonly Dictionary<string, Operation> operations = new Dictionary<string, Operation>();

        public GenerateOperation()
        {
            var storedProcedureOperation = new GenerateStoredProcedureOperation();
            AttachEvents(storedProcedureOperation);
            operations.Add(GenerateStoredProcedureOperation.Name, storedProcedureOperation);

            var bllOperation = new GenerateBLLOperation();
            AttachEvents(bllOperation);
            operations.Add(GenerateBLLOperation.Name, bllOperation);

            var serverOperation = new GenerateServerOperation();
            AttachEvents(serverOperation);
            operations.Add(GenerateServerOperation.Name, serverOperation);

            var clientOperation = new GenerateClientOperation();
            AttachEvents(clientOperation);
            operations.Add(GenerateClientOperation.Name, clientOperation);
        }

        public override void Execute(State state)
        {
            if (string.IsNullOrWhiteSpace(state.ConnectionString))
            {
                WriteMessage("Connection string is not defined! Type 'connect %connectionString%' for definition connection.", MessageType.Warning);
                return;
            }

            if (state.CommandParameters.Length == 0)
            {
                WriteMessage("Unknown command! Type 'help' for showing all available commands.", MessageType.Warning);
                return;
            }

            var commandText = "generate " + state.CommandParameters[0];
            state.CommandParameters = state.CommandParameters.Skip(1).ToArray();

            if (state.CommandParameters.Length == 0)
            {
                WriteMessage("Missing parameters! Type 'help' for showing all available commands with parameters.", MessageType.Warning);
                return;
            }

            if (operations.ContainsKey(commandText))
            {
                operations[commandText].Execute(state);
            }
            else
            {
                WriteMessage("Unknown command! Type 'help' for showing all available commands.", MessageType.Warning);
            }
        }
    }
}